package cn.edu.nju.askinginhand.util;

import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonParserTest2 {
	private static String url = "http://10.0.2.2:8080/AskingHand/";

	/**TODO : Handle Exception
	 */
	
	public static String getRootURL() {
		return url;
	}
	public static void getPDAServerData(String urlTail) throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpPost request;
		request = new HttpPost(new URI(url+"UserLoginAction?username=fdsf&password=12&type=1"));
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == 200) { // 200
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String out = EntityUtils.toString(entity);
				Map<String,Object> map = getMap(out);
				System.out.println(map.get("strResult"));
			}
		}
	}
	
	public static Map<String, Object> getMap(String jsonString)
	{
		JSONObject jsonObject;
		try
		{
			jsonObject = new JSONObject(jsonString);

			Iterator<String> keyIter = jsonObject.keys();
			String key;
			Object value;
			Map<String, Object> valueMap = new HashMap<String, Object>();
			while (keyIter.hasNext())
			{
				key = (String) keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, value);
			}
			return valueMap;
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
